#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import json
import os
import sys
import time
from pathlib import Path

import AutoExecUtils
import ServerAdapter


binPaths = os.path.split(os.path.realpath(__file__))
libPath = os.path.realpath(binPaths[0] + "/../lib")
sys.path.append(libPath)


# 这个类确保传递给程序的所有参数都是偶数对的。如果参数的数目不是偶数，它会抛出一个错误。
class EvenPairsAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        if len(values) % 2 != 0:
            raise argparse.ArgumentTypeError("The number of arguments must be even.")
        setattr(namespace, self.dest, values)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    # parser.add_argument('--rerunStrategy', type=str,  help='重跑策略', required=False)
    parser.add_argument("--combopName", type=str, help="组合工具名", required=True)
    parser.add_argument("--name", type=str, help="作业名", required=True)
    parser.add_argument("--scenarioName", type=str, default="", help="场景名", required=False)
    parser.add_argument("--source", type=str, default="combop", help="来源 itsm|combop ITSM|组合工具发起的等", required=False)
    parser.add_argument("--roundCount", type=int, default=3, help="轮次", required=False)
    parser.add_argument("--planStartTime", type=int, help="计划时间", required=False)
    parser.add_argument("--triggerType", type=str, default="", help="触发方式 auto,manual", required=False)
    parser.add_argument("--assignExecUser", type=str, default="", help="指定执行用户", required=False)
    parser.add_argument("--protocol", type=str, default="", help="执行目标，指定执行协议", required=False)
    parser.add_argument("--executeUser", type=str, default="", help="执行目标，指定执行用户", required=False)
    parser.add_argument("--inputNodeList", type=str, default="", help="执行目标，指定执行节点", required=False)

    parser.add_argument("param", type=str, nargs="*", action=EvenPairsAction, help="执行参数")
    args = parser.parse_args()

    param = {}
    for i in range(0, len(args.param), 2):
        param[args.param[i]] = args.param[i + 1]
    # for key, value in os.environ.items():
    #     print(f"{key}={value}")
    data = {
        "combopName": args.combopName,
        "name": args.name,
        "source": args.source or "combop",
        "scenarioName": args.scenarioName,
        "triggerType": args.triggerType,
        "planStartTime": args.planStartTime,
        "roundCount": args.roundCount,
        "assignExecUser": args.assignExecUser or os.environ.get("USER"),
        "param": param,
        "parentId": os.environ.get("AUTOEXEC_JOBID"),
        "invokeId": os.environ.get("AUTOEXEC_JOBID"),
    }

    if args.protocol and args.executeUser and args.inputNodeList:
        data["executeConfig"] = {"protocol": args.protocol, "executeUser": {"mappingMode": "constant", "value": args.executeUser}, "executeNodeConfig": {"inputNodeList": json.loads(args.inputNodeList)}, "whenToSpecify": "runtime"}

    context = AutoExecUtils.getAutoexecContext()
    serverAdapter = ServerAdapter.ServerAdapter(context)

    # 检查环境变量PASSTHROUGH_ENV。如果该环境变量存在，它将从环境变量中获取用户名（AUTOEXEC_USER）和密码（EXECUSER_TOKEN）
    user = None
    password = None
    if os.environ.get("PASSTHROUGH_ENV"):
        # 优先使用当前用户的token
        passThroughEnv = json.loads(os.environ.get("PASSTHROUGH_ENV"))
        if passThroughEnv.get("EXECUSER_TOKEN"):
            user = os.environ.get("AUTOEXEC_USER")
            password = passThroughEnv.get("EXECUSER_TOKEN")

    # 获取环境变量NODE_OUTPUT_PATH的值，并检查这个路径是否存在。如果存在，则获取上次操作的结果数据（prev_data），并从中获取已创建的作业ID
    outputPath = os.getenv("NODE_OUTPUT_PATH")
    if os.path.exists(outputPath):
        prev_data = AutoExecUtils.getOpPreOutput()
        if prev_data and prev_data.get("createdJobId"):
            createdJobId = prev_data.get("createdJobId")
            print("之前已创建过作业: " + str(createdJobId))
            # 重跑
            job_status = AutoExecUtils.getJobStatus({"jobId": createdJobId, "proxyToUrl": None})
            print("现在该作业状态：" + job_status)
            if job_status in ("aborted", "paused", "completed", "failed"):
                print("作业重跑")
                # 这个接口没有返回值
                serverAdapter.refireJob({"jobId": createdJobId, "type": "refireAll"}, user, password)
            exit(0)

    resp = serverAdapter.createJobFromCombop(data, user, password)
    print(resp)
    out = {"createdJobId": resp["jobId"]}
    AutoExecUtils.saveOutput(out)

    exit(0)
